package com.jielihaofeng.nettyadvance.chat.server.handler;

import com.jielihaofeng.nettyadvance.chat.message.GroupJoinResponseMessage;
import com.jielihaofeng.nettyadvance.chat.message.GroupQuitRequestMessage;
import com.jielihaofeng.nettyadvance.chat.message.GroupQuitResponseMessage;
import com.jielihaofeng.nettyadvance.chat.server.session.Group;
import com.jielihaofeng.nettyadvance.chat.server.session.GroupSession;
import com.jielihaofeng.nettyadvance.chat.server.session.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Johnnie Wind
 * @description 退出群组消息处理器
 * @date 2021/11/18 16:44
 */
@ChannelHandler.Sharable
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();

        Group group = GroupSessionFactory.getGroupSession().removeMember(groupName,username);
        // 群组存在
        if (group != null) {
            ctx.writeAndFlush(new GroupQuitResponseMessage(true, username + "退出群组" + groupName));
        }
        // 不存在
        else {
            ctx.writeAndFlush(new GroupQuitResponseMessage(false,"群组不存在"));
        }

    }
}
